#!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
selenium基类
本文件存放了selenium基类的封装方法
"""
import logging
import os
import time

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException

from common.ParseExcelFile import ParseExcel
from common.readconfig import ini
from config.conf import cm
from utils.logger import log
from utils.times import sleep


class basepage(object):
    """selenium基类"""

    def __init__(self, driver):
        # self.driver = webdriver.Chrome()
        self.driver = driver
        self.timeout = 20
        self.wait = WebDriverWait(self.driver, self.timeout)

    def get_url(self, url):
        """打开网址并验证"""
        self.driver.maximize_window()
        self.driver.set_page_load_timeout(60)
        try:
            self.driver.get(url)
            self.driver.implicitly_wait(10)
            log.info("打开网页：%s" % url)
            log.info(os.environ [ "env" ])

        except TimeoutException:
            raise TimeoutException("打开%s超时请检查网络或网址服务器" % url)




#通过excel读取方式获取元素定位方式，name，id，xpath等
    def getlocatorBy(self,key):
        global locatorBy
        excel = ParseExcel ()
        sheet = excel.get_sheet_by_name ('element')
        row = excel.get_row_num(sheet)
        try:
            for i in range (row):
                value = excel.get_value_of_cell (sheet, i + 1, 2)
                if value == key:
                    locatorBy = excel.get_value_of_cell (sheet, i + 1, 3)
                    break
        except Exception:
            pass
        return locatorBy

# 通过读取excel中的数据获取元素定位值
    def getlocatorValue(self,key):
        global locatorValue
        excel = ParseExcel ()
        sheet = excel.get_sheet_by_name ('element')
        row = excel.get_row_num(sheet)
        try:
            for i in range (row):
                value = excel.get_value_of_cell (sheet, i + 1, 2)
                if value == key:
                    locatorValue = excel.get_value_of_cell (sheet, i + 1, 4)
                    break
        except Exception:
            pass
        return locatorValue

 # 通过读取excel中的key，以元祖的形式输入定位方式和值。
    def getByLocal(self, key):
        locatorBy= self.getlocatorBy (key)
        locatorValue=self.getlocatorValue(key)
        if  locatorBy == 'name':
            return By.NAME, locatorValue
        elif locatorBy == 'id':
            return By.ID, locatorValue
        elif locatorBy == 'xpath':
            return By.XPATH, locatorValue
        elif locatorBy == 'link_text':
            return By.LINK_TEXT, locatorValue
        elif locatorBy == 'class_name':
            return By.CLASS_NAME, locatorValue
        else:
            print("暂未定义此定位元素方式")

    #js的定位封装
    def  getElement_js(self,key):
        locatorBy = self.getlocatorBy (key)
        locatorValue = self.getlocatorValue (key)
        log.info ("你的定位信息的方式为" + locatorBy);
        log.info ("你的定位信息的值为" + locatorValue);
        if locatorBy=="id":
            return self.driver.execute_script("return document.getElementById('%s')"%locatorValue)
        #如果是name，tag、classname的话返回多个元素对象的话，默认操作第一个
        elif locatorBy=="name":
            return self.driver.execute_script("return document.getElementsByName('%s')"%locatorValue)[0]
        elif locatorBy=="tag":
            return self.driver.execute_script("return document.getElementsByTagName('%s')"%locatorValue)[0]
        elif locatorBy=="css":
            pass
        else:
            log.info("定位方式不支持！")

    #显示等待定位单个元素方法方法
    def getElement(self,key):
        return WebDriverWait (self.driver, 10).until (lambda driver: driver.find_element (*(self.getByLocal(key))))# 判断元素是否存在

    #显示等待定位多个元素方法方法
    def getElements(self,key):
        return WebDriverWait (self.driver, 10).until (lambda driver: driver.find_elements(*(self.getByLocal(key))))# 判断元素集合是否存在
        # return self.driver.find_elements(*(self.getByLocal(key)))

    #通过文本直接定位对应元素
    def getElement_containstext(self,key):
        return self.driver.findElement(By.xpath("//*[contains(text(),'"+self.getlocatorValue(key)+"')]"));

    # 打开网页
    def open_url(self, url):
        log.info("打开地址"+url)
        self.driver.get(url)

    # 文本框输入数据
    def send(self, element, key):
        self.getElement(element).send_keys(key)

    def click(self, element):
        self.getElement(element).click()

    def clear(self, element):
        self.getElement(element).clear()

    def sleep(self,sec):
        time.sleep(sec)

    def get_txt(self,key):
        """
        方法用于获取元素文本值
        """
        _text = self.getElement(key).text
        return _text

    def forward (self):
        """浏览器前进"""
        self.driver.forward ()

    def back (self):
        """浏览器后退"""
        self.driver.back ()


if __name__ == "__main__":
    pass
